﻿using Generic.App.HttpApi.Controllers;
using Generic.App.HttpApi.Options;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Security.Claims;

namespace Generic.App.HttpApi.Middleware
{
    public class AutoAuthMiddleware
    {
        /// <summary>
        /// 委托
        /// </summary>
        private readonly RequestDelegate _next;
        private readonly IOptions<AutoLoginOptions>? _autoLoginOptions;

        public AutoAuthMiddleware(RequestDelegate next, IApplicationBuilder app)
        {
            _next = next;
            _autoLoginOptions = (IOptions<AutoLoginOptions>?)app.ApplicationServices.GetService(typeof(IOptions<AutoLoginOptions>));
        }

        public async Task Invoke(HttpContext context)
        {
#if DEBUG
            string? appId = _autoLoginOptions?.Value.AppId;
            if (!context.Request.Headers.ContainsKey("Authorization") && !string.IsNullOrEmpty(appId))
            {
                //Bearer Scheme(JwtBearerDefaults):The authentication handler registered for scheme 'Bearer' is 'JwtBearerHandler'
                var token = context.RequestServices.GetRequiredService<AuthController>().getJwtToken(new Claim[] { new Claim(ClaimTypes.Name, appId) });
                context.Request.Headers.Add("Authorization", "Bearer " + token);
            }
#endif
            await _next(context);
        }
    }
}
